//
//  SJTextView+Emoticon.swift
//  表情处理
//
//  Created by app;e on 15/10/21.
//  Copyright © 2015年 world. All rights reserved.
//

import UIKit

extension UITextView {
    //插入表情符号
     func insertEmoticon(emotion:SJEmoticon){
        //判断是不是删除按钮
        if emotion.removeButton == true{
            deleteBackward() //删除光标前一个文字
        }
        
        //如果是emoji表情
        if  emotion.emoji != nil {
            //selectedTextRange 选中的文字的位置
            replaceRange(selectedTextRange!, withText: emotion.emoji ?? "")
        }
        //有表情图片
        if emotion.chs != nil{
            
            //1.创建带表情属性文本
            let  imageText = SJEmoticonTextAttachment.emoticonString(emotion, font: font!)
            
            //2.获得textView的属性文本
            let attributeString = NSMutableAttributedString(attributedString: attributedText)
            
            //3.替换selectedRange当前光标所在位置的文本 为  带表情的属性文本
            attributeString.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
            
            //4.重新设置 textView的 属性文本
            //4.1 记录当前光标的位置
            let location = selectedRange.location

            //4.2 设置属性文本
            attributedText = attributeString
            //4.3 重新设置光标位置
            selectedRange = NSMakeRange(location+1, 0)
            
            //5.图片表情不会主动调用代理方法计算文本长度,需要主动调用textView的代理的textViewDidChange方法d
            delegate?.textViewDidChange!(self)
        }
    }

    ///  返回 textView 完整的表情字符串
    func emoticonText()->String {
        //        print(textView.attributedText)
        /*
        ￼{
        NSAttachment = "<NSTextAttachment: 0x608000049e20>";
        NSFont = "<UICTFont: 0x61200001a140> font-family: \".SFUIText-Regular\"; font-weight: normal; font-style: normal; font-size: 14.00pt";
        }
        有NSAttachment key的就是代表有配图
        */
        
        //遍历textView的 属性文本
        var textM: String = ""
        attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _ ) -> Void in
            
            if let attachment = dict["NSAttachment"] as? SJEmoticonTextAttachment {
                //拼接 表情文字
                textM += attachment.chs ?? ""
                
            }else{
                //拼接 文本内容
                let str = (self.attributedText.string as NSString).substringWithRange(range)
                textM += str
            }
        }
        return textM
    }

}